package net.zjitc.dao.impl;

import net.zjitc.dao.UserDao;
import net.zjitc.domain.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by Administrator on 2017/2/27.
 */
@Repository
public class UserDaoImpl implements UserDao {
    @Resource
    private SessionFactory sessionFactory;

    @Override
    public User findByUsernamePassword(String username, String password) {

/*        for (User u:users){
            if (u.getUsername().equals(username)&&u.getPassword().equals(password)){
                return u;
            }
        }*/
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        User user = (User) session.createQuery(
                "from User a where a.username = ? and a.passworld = ?")
                .setParameter(0,username)
                .setParameter(1,password)
                .uniqueResult();
        transaction.commit();
        session.close();
        return user;
    }

    @Override
    public Boolean findByRegistr(String username, String password) {
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        User u = new User();
        u.setUsername(username);
        u.setPassworld(password);

        User user = (User) session.createQuery(
                "from User a where a.username = ?")
                .setParameter(0,username)
                .uniqueResult();
        if (user!=null){
            transaction.commit();
            session.close();
            return false;
        }else {
            session.save(u);
            transaction.commit();
            session.close();
            return true;
        }

    }

    @Override
    public List<User> findAll() {
        return getSession().createQuery("from User ")
                .list()
                ;
    }

    private Session getSession() {
        Session session = sessionFactory.getCurrentSession();
        return session;
    }


}
